#include "gauss.h"

Gauss::Gauss()
{
    int flag=0,i=0;
    QSqlQuery query;
    QString str;
    double data[2],amp,ys,yss;
    double mem[4]={0}; // 0 - x0; 1 - y0; 2 - y'0; 3 - y''0
    query.exec("SELECT * FROM wave WHERE id ="+str.setNum(1));
    query.first();	//set position
    data[0]=query.value(9).toDouble();
    amp=query.value(32).toDouble();
    ys=0;
    yss=0;
    while (flag==0 && query.isValid())
        {
            query.exec("SELECT * FROM wave WHERE id ="+str.setNum(i+2));
            query.first();	//set position
            data[0]=query.value(9).toDouble();
            data[1]=query.value(32).toDouble()/amp;
            ys=(data[1]-mem[1])/(data[0]-mem[0]);
            yss=(ys-mem[2])/(data[0]-mem[0]);
            if (i>2 && yss*mem[3]<0)
            {
                scaleY=(mem[1]-1/sqrt(M_E))/(1-1/sqrt(M_E));
                sig=1/(1-scaleY)/sqrt(2*M_PI);
                scaleX=sig/mem[0];
                mat=0;
                flag=1;
            }
            i++;
            mem[0]=data[0];
            mem[1]=data[1];
            mem[2]=ys;
            mem[3]=yss;
        }
    if (!flag)
    {
        mat=0;
        sig=0;
        scaleX=0;
        scaleY=0;
    }
}

void Gauss::printGauss(QTextBrowser *text)
{
    QString str;
    text->append("mat:\t"+str.setNum(mat));
    text->append("sigma:\t"+str.setNum(sig));
    text->append("scaleX:\t"+str.setNum(scaleX));
    text->append("scaleY:\t"+str.setNum(scaleY));
}

double Gauss::getValue(double x)
{
    double value;
    x*=scaleX;
    value=scaleY+1/sig/sqrt(2*M_PI)*exp(-1*pow((x-mat)/sig,2)/2);
    return value;
}

bool Gauss::saveGauss(QFile *writeFile)
{
    QString str;
    QTextStream stream(writeFile);
    stream << "mat:\t"+str.setNum(mat) << endl;
    stream << "Sigma:\t"+str.setNum(sig) << endl;
    stream << "ScaleX:\t"+str.setNum(scaleX) << endl;
    stream << "ScaleY:\t"+str.setNum(scaleY) << endl;
    return 1;
}
